import Request from "./request"
import { BASE_URL, TIME_OUT } from "./request/config"
import { ElMessage } from "element-plus"

let over: boolean = true
// 创建一个实例
const Requests = new Request({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  // 实例的拦截器
  interceptors: {
    // 请求成功的拦截
    requestInterceptor: config => {
      // 需要携带token给服务器
      const token = localStorage.getItem("token")
      if (token) {
        // axios AxiosRequestConfig 里的 header 的定义可以是undefined
        if (config && config?.headers) {
          config.headers.Authorization = token
        }
      }
      return config
    },
    // 请求失败的拦截
    requestInterceptorCatch: err => {
      console.log(err)
      return err
    },
    // 响应成功的拦截
    responseInterceptor: res => {
      if (res.status == 202) {
        ElMessage.error(res.data.message)
      }
      return res.data
    },
    // 响应失败的拦截
    responseInterceptorCatch: err => {
      if (err.message === "timeout of 5000ms exceeded") {
        ElMessage.error("请求超时")
      }
      switch (err.response.status) {
        case 415:
          // 登录失效
          localStorage.removeItem("token")
          ElMessage({
            message: err.response.data.message,
            type: "error",
            onClose: function () {
              window.location.href = "/login"
            }
          })
          break
        case 401:
        case 403:
        case 500:
          if (over) {
            over = false
            ElMessage({
              message: err.response.data.message,
              type: "error",
              onClose: function () {
                over = true
              }
            })
          }
          break
        default:
          break
      }
      return err
    }
  }
})

export default Requests
